package tw.com.hitevision.whiteboard.android.widgets.floatView.widget.activityfloat

import android.app.Activity
import android.view.View
import android.widget.FrameLayout
import tw.com.hitevision.whiteboard.android.widgets.floatView.data.FloatConfig

class ActivityFloatManager(val activity: Activity) {

    // get the screen FrameLayout by DecorView as parentLayout
    private var parentFrame: FrameLayout =
        activity.window.decorView.findViewById(android.R.id.content)

    /**
     * create Activity floating view
     */
    fun createFloat(config: FloatConfig) {

        val floatingView = FloatingView(activity).apply {

            tag = getTag(config.floatTag)

            layoutParams = FrameLayout.LayoutParams(
                if (config.widthMatch) FrameLayout.LayoutParams.MATCH_PARENT else FrameLayout.LayoutParams.WRAP_CONTENT,
                if (config.heightMatch) FrameLayout.LayoutParams.MATCH_PARENT else FrameLayout.LayoutParams.WRAP_CONTENT
            ).apply {
                if (config.locationPair == Pair(0, 0)) gravity = config.gravity
            }
            config.anchorPair = config.locationPair

            setFloatConfig(config)
        }

        parentFrame.addView(floatingView)

        config.layoutView = floatingView
        config.callbacks?.createdResult(true, null, floatingView)
        config.floatCallbacks?.builder?.createdResult?.invoke(true, null, floatingView)
    }

    /**
     * dismiss floating view
     */
    fun dismiss(tag: String?) = floatingView(tag)?.exitAnim()

    /**
     *  set floating view visibility
     */
    fun setVisibility(tag: String?, visibility: Int) = floatingView(tag)?.apply {
        this.visibility = visibility
        if (visibility == View.GONE) {
            config.callbacks?.hide(this)
            config.floatCallbacks?.builder?.hide?.invoke(this)
        } else {
            config.callbacks?.show(this)
            config.floatCallbacks?.builder?.show?.invoke(this)
        }
    }

    /**
     *  is Show
     */
    fun isShow(tag: String? = null): Boolean = floatingView(tag)?.visibility == View.VISIBLE

    /**
     *  set drag enable
     */
    fun setDragEnable(dragEnable: Boolean, tag: String? = null) {
        floatingView(tag)?.config?.dragEnable = dragEnable
    }

    /**
     *  get floating view
     */
    fun getFloatView(tag: String? = null): View? = floatingView(tag)?.config?.layoutView

    /**
     *  get floating view config
     */
    fun getFloatViewConfig(tag: String? = null): FloatConfig? = floatingView(tag)?.config

    /**
     *  get floating view outside
     */
    private fun floatingView(tag: String?): FloatingView? = parentFrame.findViewWithTag(getTag(tag))

    /**
     *  if tag is null using activity name as tag
     */
    private fun getTag(tag: String?) = tag ?: activity.componentName.className

}